package com.c.ctgproject.http

import android.content.Context
import com.c.ctgproject.ui.login.LoginActivity
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.LoadingDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import java.lang.Exception

open class MyObserverHandlerLoading(private val context: Context, private val loading: LoadingDialog? = null, private val refresh: SmartRefreshLayout? = null, private val zeroIsSuccess: Boolean = false, private val block: (String) -> Unit) : Observer<ResponseBody> {

    //加载完成 进度条消失
    override fun onComplete() {
        refresh?.over()
        loading?.dismiss()
    }

    //加载开始 展示进度条
    override fun onSubscribe(d: Disposable) {
        loading?.show()
    }

    //加载完成回调
    override fun onNext(t: ResponseBody) {
        val str = t.string().handlerNull()
//        MyLog.d("这是啥啊:$str")
//        val msg = JSONObject(str).optString("msg", "")
//        if (msg.isNotEmpty() && "重新登录" in msg) {
//            context.showToast(msg)
//            userToken=""
//            context.startActivity<LoginActivity>()
//        }
        try {
            if (zeroIsSuccess) {
                context.handlerDataZeroIsSuccess(str) {
                    block(str)
                }
            } else {
                context.handlerDataGQ(str) {
                    block(str)
                }
            }
        } catch (e: Exception) {
            MyLog.d("错误:${e.message.handlerNull()}")
            context.showToast(e.message.handlerNull())
        }
    }

    //出现错误 进度条消失 按需求展示错误页面
    override fun onError(e: Throwable) {
        refresh?.over()
        loading?.dismiss()
        if ("401" in e.message.handlerNull()){
            userToken=""
            context.startActivity<LoginActivity>()
            context.showToast("您的账号在其他地方被登录了，若要继续进行操作，请您重新登录")
        }else{
            context.showToast(e.message.handlerNull())
        }
    }
}

